package com.kebaijia.clone;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

public class TestClone {

	public static void main(String[] args) throws Exception{
		//FileOutputStream fos = new FileOutputStream("workers.dat");
		//ObjectOutputStream out = new ObjectOutputStream(fos);
		
		Address a1 = new Address();
		Worker w = new Worker("Liucy" , 30 , a1);
		//out.writeObject(w);
		
		//Worker w2 = 和w对象属性完全一致的新对象
		Object o = w.clone();
		Worker w2 = (Worker)o;
		System.out.println(w == w2);  //false
		System.out.println(w.addr == w2.addr);//true
		
		
		//out.writeObject(w2);
		//out.close();
		
		/*
		FileInputStream fis = new FileInputStream("workers.dat");
		ObjectInputStream in= new ObjectInputStream(fis);
		Object o1 = in.readObject();
		Object o2 = in.readObject();
		System.out.println(o1);
		System.out.println(o2);
		in.close();
		*/
	}
}
class Worker implements Serializable,Cloneable{
	String name;
	int age;
	Address addr;
	public Worker(String name, int age , Address addr) {
		super();
		this.name = name;
		this.age = age;
		this.addr = addr;
	}
	@Override
	public String toString() {
		return "Worker [name=" + name + ", age=" + age + "]";
	}
	
	@Override
	public Object clone() throws CloneNotSupportedException {
		Object o = null;
		try {
			ByteArrayOutputStream bos = new ByteArrayOutputStream();
			ObjectOutputStream out = new ObjectOutputStream(bos);
			out.writeObject(this);
			byte[] bs = bos.toByteArray();
			out.close();
			
			ByteArrayInputStream bis = new ByteArrayInputStream(bs);
			ObjectInputStream in = new ObjectInputStream(bis);
			o = in.readObject();
			in.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return o;
	}
}

class Address implements Serializable{
	String addr;
}





